<template>
    <div
        class="
            w-4/5
            h-4/5
            bg-white
            rounded-3xl
            flex flex-col
            p-2
            items-center
            Serif-Bolder
            relative
        "
    >
        <div
            class="
                absolute
                top-4
                right-4
                Icon
                text-2xl
                hover:bg-gray-100
                rounded-lg
            "
            @click="$emit('close')"
        >
            close
        </div>
        <div class="title text-3xl my-4 text-green-500">{{ packageName }}</div>
        <div class="text-yellow-500 p-4 w-full">
            默认文件
            <span class="Icon mx-4"> article </span>
            {{ info.default }}
        </div>
        <div class="w-full m-4 overflow-y-scroll">
            <div
                class="flex flex-row cursor-pointer"
                @click="backto"
                v-show="backPath.length"
            >
                <div class="Icon text-blue-500 mx-4">reply</div>
                <div v-for="(path, index) in backPath" :key="path + index">
                    {{ path }} /
                </div>
            </div>

            <div
                v-for="item in looking.files"
                :key="item.hash"
                class="
                    flex flex-row
                    items-center
                    cursor-pointer
                    hover:bg-gray-100
                    rounded-lg
                    transition
                    px-4
                    py-1
                "
            >
                <span
                    class="Icon"
                    @click="jumpto(item)"
                    :style="{
                        color: item.type === 'file' ? '#777' : '#f6d572',
                    }"
                >
                    {{ item.type === "file" ? "text_snippet" : "folder" }}
                </span>
                <div class="flex-grow mx-4" @click="jumpto(item)">
                    {{ item.name }}
                </div>
                <div v-if="item.type === 'file'" class="text-sm text-green-600">
                    {{ item.size | bytesToSize }}
                </div>
                <div
                    class="Icon flex flex-row text-xl"
                    style="width: fit-content"
                    v-if="item.type === 'file'"
                >
                    <div @click="Download(item)">download</div>
                    <div @click="copyCode(item)">content_copy</div>
                    <div @click="copyHTML(item)">code</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import copy from "@/utils/copy.js";
import aDownload from "@/utils/aDownload.js";
export default {
    props: {
        type: {
            type: String,
            default: "npm",
        },
        target: {},
    },
    filters: {
        bytesToSize(bytes) {
            if (bytes === 0) return "0 B";
            let k = 1024,
                sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
                i = Math.floor(Math.log(bytes) / Math.log(k));
            return (bytes / Math.pow(k, i)).toFixed(2) + " " + sizes[i];
        },
    },

    watch: {
        target({ version, name }) {
            console.log("加载中", version, name);
            this.getVersion().then(() => this.getInfo());
        },
    },
    data() {
        return {
            looking: {
                files: [],
            },
            versions: [],
            backPath: [],
            info: { default: "", files: [] },
        };
    },

    computed: {
        packageName() {
            if (this.type === "gh") {
                return this.target.owner.name + "/" + this.target.name;
            } else {
                return this.target.name;
            }
        },
        version() {
            return this.versions[0];
        },
    },
    methods: {
        Download(item) {
            const url = this.genURL(item);
            fetch(url)
                .then((res) => res.blob())
                .then((res) => {
                    aDownload(res, item.name);
                });
        },
        genURL(item) {
            return (
                "https://cdn.jsdelivr.net/" +
                [
                    this.type,
                    this.packageName + (this.version ? `@${this.version}` : ""),
                    ...this.backPath,
                    item.name,
                ].join("/")
            );
        },
        copyHTML(item) {
            let url = this.genURL(item);

            if (/\.js$/.test(url)) url = `<script src="${url}"><\/script>`;
            if (/\.css$/.test(url))
                url = `<link rel="stylesheet" type="text/css" href="${url}" />`;
            copy(url).then(() => console.info("复制代码成功"));
        },
        copyCode(item) {
            const url = this.genURL(item);

            copy(url).then(() => console.info("复制代码成功"));
        },
        jumpto(item) {
            if (item.type !== "file") {
                const father = this.looking;
                this.looking = item;
                this.looking.father = father;
                this.backPath.push(item.name);
            }
        },
        backto() {
            this.looking = this.looking.father;
            this.backPath.pop();
        },
        async getVersion() {
            const { versions } = await fetch(
                `https://data.jsdelivr.com/v1/package/${this.type}/${this.packageName}`
            ).then((res) => res.json());
            this.versions = versions;
        },
        async getInfo() {
            this.info = await fetch(
                `https://data.jsdelivr.com/v1/package/${this.type}/${this.packageName}@${this.version}`
            ).then((res) => res.json());
            const father = this.looking;
            this.looking = this.info;
            this.looking.father = father;
        },
    },
};
</script>

<style lang="less" scoped></style>
